package com.example.jobback.service.seeker.impl;

import com.example.jobback.config.AuthConfig;
import com.example.jobback.mapper.CollectMapper;
import com.example.jobback.mapper.ProjectExperienceMapper;
import com.example.jobback.mapper.SeekerMapper;
import com.example.jobback.mapper.WorkExperienceMapper;
import com.example.jobback.po.ProjectExperience;
import com.example.jobback.po.Seeker;
import com.example.jobback.po.User;
import com.example.jobback.po.WorkExperience;
import com.example.jobback.req.seeker.experience.project.ProjectExperienceReq;
import com.example.jobback.req.seeker.experience.work.WorkExperienceReq;
import com.example.jobback.req.seeker.profile.SeekerReq;
import com.example.jobback.resp.seeker.experience.project.ProjectExperienceResp;
import com.example.jobback.resp.seeker.experience.work.WorkExperienceResp;
import com.example.jobback.resp.seeker.profile.SeekerResp;
import com.example.jobback.result.Result;
import com.example.jobback.service.common.UserCommonService;
import com.example.jobback.service.seeker.SeekerProfileService;
import com.example.jobback.util.PhoneNumberUtils;
import com.example.jobback.util.SecureEncryptionUtil;
import com.example.jobback.util.TLUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.example.jobback.util.RedisConstants.SEEKER_KEY;
import static com.example.jobback.util.RedisConstants.SEEKER_TTL;

/**
 * @ClassName: SeekerProfileServiceImpl
 * @Description:求职者-个人中心实现类
 * @Author: lhb
 * @Date: 2025/6/21
 */
@Service
public class SeekerProfileServiceImpl implements SeekerProfileService {

    private final AuthConfig authConfig;

    private final UserCommonService userCommonService;

    private final ProjectExperienceMapper projectExperienceMapper;


    private final WorkExperienceMapper workExperienceMapper;

    private final SeekerMapper seekerMapper;

    public SeekerProfileServiceImpl(AuthConfig authConfig,
                                    UserCommonService userCommonService,
                                    SeekerMapper seekerMapper,
                                    ProjectExperienceMapper projectExperienceMapper,
                                    WorkExperienceMapper workExperienceMapper
                                    ) {
        this.authConfig = authConfig;
        this.userCommonService = userCommonService;
        this.seekerMapper = seekerMapper;
        this.projectExperienceMapper = projectExperienceMapper;
        this.workExperienceMapper = workExperienceMapper;
    }

    /**
     * @Description: 获取基本信息
     * @return Result<SeekerResp>
     * @Author lhb
     * @CreateTime 2025/6/21 14:46
     */
    @Override
    public Result<SeekerResp> getBasicMessage() {
        Seeker seeker= TLUtil.get(TLUtil.S);
        String phone = null;
        try {
            phone = SecureEncryptionUtil.decrypt(seeker.getPhoneAes(), authConfig.getPhoneSecret());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        SeekerResp seekerResp = new SeekerResp();
        Long age=0L;
        LocalDateTime birthDate=seeker.getBirthDate();
        if (birthDate!=null) {
            age = (long) Period.between(LocalDate.from(birthDate), LocalDate.now()).getYears();
        }
        seekerResp.setAge(age);
        //带*处理
        String maskedPhone = PhoneNumberUtils.maskPhoneNumber(phone);
        seekerResp.setPhone(maskedPhone);
        BeanUtils.copyProperties(seeker, seekerResp);
        return Result.success(seekerResp);
    }

    /**
     * @Description: 编辑基本信息
     * @param req
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 14:48
     */
    @Override
    public Result<Object> editBasicMessage(SeekerReq req) {
        Seeker seeker=TLUtil.get(TLUtil.S);
        BeanUtils.copyProperties(req, seeker);
        //修改user的各角色的共同信息
        User user=new User();
        BeanUtils.copyProperties(seeker, user);
        if(userCommonService.editBasicMessage(user)==0) throw new RuntimeException("修改失败");
        //修改求职者的个别信息
        if(seekerMapper.editBasicMessage(seeker)==0) throw new RuntimeException("修改失败");
        String token = userCommonService.setRedisUser(seeker,seeker.getUserId(),SEEKER_KEY,authConfig.getJwtSeekerSecret(),SEEKER_TTL, TimeUnit.DAYS);
        if(token==null) throw new RuntimeException("修改失败");
        return Result.success(token);
    }

    /**
     * @Description: 上传头像
     * @param file
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 14:51
     */
    @Override
    public Result<Object> uploadAvatar(MultipartFile file) {
        Seeker seeker=TLUtil.get(TLUtil.S);
        //user对象的userid
        Long userId=seeker.getUserId();
        String catalog="Avatar/User";
        String lastUrl= userCommonService.uploadAvatar(userId,file,catalog);
        if(lastUrl==null) throw new RuntimeException("上传失败");
        if(userCommonService.updateUserAvatar(userId,lastUrl)==0) throw new RuntimeException("上传失败");
        seeker.setAvatar(lastUrl);
        String token = userCommonService.setRedisUser(seeker,seeker.getUserId(),SEEKER_KEY,authConfig.getJwtSeekerSecret(),SEEKER_TTL,TimeUnit.DAYS);
        return Result.success(token);
    }

    /**
     * @Description: 编辑项目经历
     * @param reqList
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 14:52
     */
    @Override
    public Result<Object> editProjectExperience(List<ProjectExperienceReq> reqList) {
        Seeker seeker = TLUtil.get(TLUtil.S);
        Long userId=seeker.getUserId();
        List<ProjectExperience> poList=new ArrayList<>();
        for (ProjectExperienceReq req:reqList){
            ProjectExperience projectExperience=new ProjectExperience();
            BeanUtils.copyProperties(req, projectExperience);
            projectExperience.setUserId(userId);
            poList.add(projectExperience);
        }
        //判断前端穿过来的ids是否是mysql的ids的子集
        List<Long> ids=projectExperienceMapper.getSeekerProExperienceIds(userId);
        if(!ids.isEmpty()){
            for (ProjectExperienceReq req:reqList){
                Long id=req.getId();
                if(id!=null) ids.remove(id);
            }
            if(!ids.isEmpty()){
                for (Long id:ids){
                    if(projectExperienceMapper.deleteProjectExperienceById(id,userId)==0) throw new RuntimeException("修改失败");
                }
            }
        }
        for (ProjectExperience element:poList){
            if(element.getId() ==-1){
                if(projectExperienceMapper.insertProjectExperience(element)==0) throw new RuntimeException("修改失败");
                continue;
            }
            if(projectExperienceMapper.editProjectExperience(element)==0) throw new RuntimeException("修改失败");
        }
        String token = userCommonService.updateRedisUserToken(seeker.getUserId(), SEEKER_KEY, authConfig.getJwtSeekerSecret(), SEEKER_TTL, TimeUnit.DAYS);
        if(token==null) throw new RuntimeException("生成token失败");
        return Result.success(token);
    }

    /**
     * @Description: 获取项目经历
     * @return Result<List<ProjectExperienceResp>>
     * @Author lhb
     * @CreateTime 2025/6/21 14:53
     */
    @Override
    public Result<List<ProjectExperienceResp>> getProjectExperience() {
        Seeker seeker=TLUtil.get(TLUtil.S);
        Long userId=seeker.getUserId();
        List<ProjectExperienceResp> respList=projectExperienceMapper.getProjectExperience(userId);
        return Result.success(respList);
    }

    /**
     * @Description: 编辑工作经历
     * @param reqList
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 14:54
     */
    @Override
    public Result<Object> editWorkExperience(List<WorkExperienceReq> reqList) {
        Seeker seeker = TLUtil.get(TLUtil.S);
        Long userId=seeker.getUserId();
        List<WorkExperience> poList=new ArrayList<>();
        for (WorkExperienceReq req:reqList){
            WorkExperience workExperience=new WorkExperience();
            BeanUtils.copyProperties(req, workExperience);
            workExperience.setUserId(userId);
            poList.add(workExperience);
        }
        //判断前端穿过来的ids是否是mysql的ids的子集
        List<Long> ids=workExperienceMapper.getSeekerWorkExperienceIds(userId);
        if(!ids.isEmpty()){
            for (WorkExperience element:poList){
                Long id=element.getId();
                if(id!=null) ids.remove(id);
            }
            if(!ids.isEmpty()){
                for (Long id:ids){
                    if(workExperienceMapper.deleteWorkExperienceById(id,userId)==0) throw new RuntimeException("修改失败");
                }
            }
        }
        for (WorkExperience element:poList){
            if(element.getId() ==-1){
                if(workExperienceMapper.insertWorkExperience(element)==0) throw new RuntimeException("修改失败");
                continue;
            }
            if(workExperienceMapper.editWorkExperience(element)==0) throw new RuntimeException("修改失败");
        }
        String token = userCommonService.updateRedisUserToken(seeker.getUserId(), SEEKER_KEY, authConfig.getJwtSeekerSecret(), SEEKER_TTL, TimeUnit.DAYS);
        if(token==null) throw new RuntimeException("生成token失败");
        return Result.success(token);
    }

    /**
     * @Description: 获取工作经历
     * @return Result<List<WorkExperienceResp>>
     * @Author lhb
     * @CreateTime 2025/6/21 14:55
     */
    @Override
    public Result<List<WorkExperienceResp>> getWorkExperience() {
        Seeker seeker=TLUtil.get(TLUtil.S);
        Long userId=seeker.getUserId();
        List<WorkExperienceResp> respList=workExperienceMapper.getWorkExperience(userId);
        return Result.success(respList);
    }
}
